import { useCallback, useState } from 'react';
import { debounce } from 'lodash';
import { message } from 'antd';

export function useDebouncedClickWithMessage(
    action: () => Promise<any>,
    delay: number = 1000,
    messageText: string = '操作过于频繁，请稍后再试！'
) {
    const [isLoading, setIsLoading] = useState(false);

    const debouncedAction = useCallback(
        debounce(async () => {
            if (isLoading) {
                message.warning(messageText);
                return;
            }
            setIsLoading(true);
            try {
                await action();
            } finally {
                setTimeout(() => setIsLoading(false), delay);
            }
        }, delay),
        [action, delay, messageText]
    );

    return { debouncedAction, isLoading };
}